//
//  HDNearbyViewController.m
//  HDecoration
//
//  Created by 曹群 on 15/8/16.
//  Copyright (c) 2015年 HDecoration. All rights reserved.
//

#import "HDNearbyViewController.h"
#import <iflyMSC/iflyMSC.h>

@interface HDNearbyViewController ()

@property(nonatomic,strong)HDOrderView *orderView;
@property(nonatomic,strong)HDCustomerInfo *currentOrderInfo;
@property(nonatomic,assign)int interval;
@property(nonatomic,strong)AsyncSocket * asyncSocket;
@property(nonatomic,assign)BOOL bReconnet;
@property (nonatomic)  DOImageView* tipView;
@end

@implementation HDNearbyViewController
@synthesize asyncSocket;

- (void)initUI
{
    [self.view addSubview:self.orderView];
    [self.view addSubview:self.tipView];

}

-(DOImageView*)tipView
{
    if (_tipView==nil)
    {
        float x=(APPFRAME.size.width-216)/2.0;
        float y=(SCREENFRAME.size.height-236)/2.0;
        CGRect rect=CGRectMake(x,y, 216, 118);
        _tipView=[[DOImageView alloc] initWithFrame:rect];
        _tipView.imgURLStr=@"bg0";
    }
    return _tipView;
}

- (void)orderViewAcceptOrder
{
    NSDictionary* params=@{
                           @"coach_id":netEngine.coachInfo.m_id,
                           @"id":self.currentOrderInfo.order_id,
                           @"coach_name":netEngine.coachInfo.real_name,
                           @"coach_no":netEngine.coachInfo.coach_no,
                           };
    [netEngine RequestAcceptOrderWithTarget:self.VctrID hudView:self.contentView Data:params];
    
}

-(void)updateViewController:(NSNotification *)note
{
    NSDictionary* dic=note.userInfo;
    if ([dic objectForKey:Receiver]==self.VctrID)
    {
        if (dic[@"AcceptOrder"]!=nil)
        {
            [[NSNotificationCenter defaultCenter] postNotificationName:HDRefreshOrderListNotification object:nil];
            [self.orderView dismiss];
            self.tipView.hidden=NO;
        }
    }
}

- (void)setOrderType:(HDOrderType)orderType
{
    _orderType = orderType;
}


#pragma mark  socket

-(void)createSocketRequest
{
    asyncSocket = [[AsyncSocket alloc] initWithDelegate:self];
    [asyncSocket setRunLoopModes:[NSArray arrayWithObject:NSRunLoopCommonModes]];
    
    NSError *err = nil;
    if(![asyncSocket connectToHost:netEngine.coachInfo.cservice onPort:[netEngine.coachInfo.pport intValue] error:&err])
    {
        NSLog(@"Error: %@", err);
    }
}


- (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port
{
    NSString* strContent=[NSString stringWithFormat:@"ID:%@",netEngine.coachInfo.m_id];
    NSData* aData= [strContent dataUsingEncoding: NSUTF8StringEncoding];
    
    
    Byte *testByte = (Byte *)[aData bytes];
    aData=[NSData dataWithBytes:testByte length:[aData length]];
    [sock writeData:aData withTimeout:-1 tag:1];
    
    [sock readDataWithTimeout:-1 tag:0];
}

- (void)onSocketDidDisconnect:(AsyncSocket *)sock
{
    if (self.bReconnet)
    {
        [self createSocketRequest];
    }
}

-(void) onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
    NSString *result=[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSData *responseData = [result dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary* json =[NSJSONSerialization
                         JSONObjectWithData:responseData
                         options:kNilOptions
                         error:nil];
    
    if (json!=nil && [json isKindOfClass:[NSArray class]])
    {
        NSDictionary* item=((NSArray*)json)[0];
        if (item[@"end"]!=nil)
        {
             [self.orderView dismiss];
            self.tipView.hidden=NO;
        }
        else
        {
            [self parseOrder:item];
        }
    }
    
    NSLog(@"%@",json);
    
    
    
    [sock readDataWithTimeout:-1 tag:0];
}


-(void)onSocket:(AsyncSocket *)sock didWriteDataWithTag:(long)tag
{
    NSLog(@"didWriteDataSuccess");
}


- (void)viewWillDisappear:(BOOL)animated
{
     self.bReconnet=NO;
    NSData* aData= [@"quit" dataUsingEncoding: NSUTF8StringEncoding];
    [asyncSocket writeData:aData withTimeout:-1 tag:1];
    
    [asyncSocket disconnect];
    asyncSocket=nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    self.bReconnet=YES;
    [self createSocketRequest];
}

-(void)parseOrder:(NSDictionary*)data
{
    HDCustomerInfo *customerInfo = [[HDCustomerInfo alloc] init];
    //添加解析
    int category=[[HDUtil check:data[@"category"]] intValue];
    NSArray* array=@[@"无",@"科目一",@"科目二",@"科目三",@"科目四",@"科目五",@"科目六"];
    category=MIN(category, (int)array.count-1);
    customerInfo.subject = array[category];
    customerInfo.photoUrl = [HDUtil check:data[@"user_picture"]];
    customerInfo.stationTime = [HDUtil check:data[@"total_hours"]];
    customerInfo.name=[HDUtil check:data[@"student_name"]];
    customerInfo.type=[HDUtil check:data[@"car_type"]];
    customerInfo.remark = [HDUtil check:data[@"remark"]];
    customerInfo.price = [HDUtil check:data[@"order_money"]];
    customerInfo.practicePosition = [HDUtil check:data[@"training_field"]];
    customerInfo.needCompany = [[HDUtil check:data[@"ispick"]] boolValue];
    customerInfo.order_id=[HDUtil check:data[@"id"]];
    customerInfo.learnTime = [HDUtil check:data[@"order_hours"]];
    
    NSArray* array01=@[@"无",@"待支付",@"退单申请中",@"已支付",@"已抢单",@"已拒绝",@"进行中",@"已完成",@"已退单完成",@"退单已拒绝"];
    int state=[[HDUtil check:data[@"state"]] intValue];
    state=MIN(state, (int)array01.count-1);
    customerInfo.orderStatus = array01[state];
    
    int orderType=[[HDUtil check:data[@"order_type"]] intValue];
    customerInfo.orderType=(orderType==1)?HDOrderTypeLearn:HDOrderTypePractice;
    customerInfo.phoneNumber=[HDUtil check:data[@"mobile_no"]];
    customerInfo.startTime=[HDUtil checkNumber:data[@"start_time"]];
    customerInfo.endTime=[HDUtil checkNumber:data[@"end_time"]];
    customerInfo.price = [HDUtil check:data[@"order_money"]];
    
    NSString* xy=[HDUtil check:data[@"xy"]];
    xy=[xy stringByReplacingOccurrencesOfString:@"(" withString:@""];
    xy=[xy stringByReplacingOccurrencesOfString:@")" withString:@""];
    NSArray* array02=[xy componentsSeparatedByString:@","];
    if(array02.count>1)
    {
        customerInfo.latitude=[array02[0] floatValue];
        customerInfo.longitude=[array02[1] floatValue];
    }
    else
    {
        customerInfo.xy=@"";
    }
    customerInfo.location=[HDUtil check:data[@"address"]];
    customerInfo.content=[HDUtil check:data[@"content"]];
    
    self.currentOrderInfo = customerInfo;
    
    if (customerInfo.orderType==self.orderType)
    {
        [self.orderView showWithData:self.currentOrderInfo];
        [netEngine startBroadcast:self.currentOrderInfo.content];
        self.tipView.hidden=YES;
    }
}


//##############################################


-(void)testDataFunc
{
}

- (void)showOrder:(NSTimer *)timer
{
    self.interval++;
    self.currentOrderInfo = timer.userInfo[self.interval%2];
    [self.orderView showWithData:self.currentOrderInfo];
}

#pragma mark - getters
- (HDOrderView *)orderView
{
    if (!_orderView) {
        _orderView = [[HDOrderView alloc] initWithFrame:CGRectMake(0, 0, APPFRAME.size.width, self.view.height)];
        _orderView.separateOrderType = YES;
        _orderView.delegate = (id)self;
    }
    return _orderView;
}



@end
